#!/bin/bash

# delete_group_users.sh
# 功能说明:
# 1. 删除属于指定组的所有用户。
# 2. 支持模拟模式，仅列出将要删除的用户，而不实际执行删除。
# 3. 确保系统用户和关键用户（如 root）不会被误删。

# 模拟模式标志
simulate=false

# 排除的关键用户
EXCLUDED_USERS=("root" "nobody")

# 获取属于指定组的用户
get_group_users() {
  local group="$1"

  # 检查组是否存在
  if ! getent group "$group" &>/dev/null; then
    echo "Group '$group' does not exist."
    exit 1
  fi

  # 获取组内用户
  local users=$(getent group "$group" | awk -F: '{print $4}')
  echo "$users"
}

# 删除用户
delete_user() {
  local username="$1"

  # 检查用户是否在排除列表中
  if [[ " ${EXCLUDED_USERS[*]} " =~ " $username " ]]; then
    echo "User $username is excluded from deletion."
    return
  fi

  # 检查用户是否存在
  if id "$username" &>/dev/null; then
    echo "Deleting user $username..."
    sudo userdel -r "$username" && echo "User $username has been deleted." || echo "Failed to delete user $username."
  else
    echo "User $username does not exist. Skipping..."
  fi
}

# 主函数
main() {
  if [[ $# -lt 1 ]]; then
    echo "Usage: $0 [group_name] [-s|--simulate]"
    echo "  group_name: Specify the group whose users will be deleted."
    echo "  -s, --simulate: Simulate mode, only list users without deleting."
    exit 1
  fi

  local group="$1"
  shift

  # 检查是否启用模拟模式
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -s|--simulate)
        simulate=true
        ;;
      *)
        echo "Invalid argument: $1"
        exit 1
        ;;
    esac
    shift
  done

  # 获取组内用户
  local users=$(get_group_users "$group")
  if [[ -z "$users" ]]; then
    echo "No users found in group '$group'."
    exit 0
  fi

  # 分割用户列表
  IFS=',' read -ra user_array <<< "$users"

  echo "The following users belong to group '$group':"
  for user in "${user_array[@]}"; do
    echo "  - $user"
  done

  # 模拟模式
  if [[ "$simulate" == true ]]; then
    echo "Simulate mode: No users will be deleted."
    exit 0
  fi

  # 确认删除
  echo "The above users will be deleted. Are you sure? (yes/no)"
  read -r confirm
  if [[ "$confirm" != "yes" ]]; then
    echo "Operation aborted."
    exit 0
  fi

  # 删除用户
  for user in "${user_array[@]}"; do
    delete_user "$user"
  done

  echo "Deletion process completed."
}

# 执行主函数
main "$@"

